const util = require('./utils.js');
const resource = require('./resource.js');
class Http extends resource{

    constructor(client_sock){
        super();
        /* 客户端sock */
        this.client_sock = client_sock;
        /* 请求头 */
        this.header={};
        /* 响应头 */
        this.head_res={};

        /* 执行状态 1:start,2:execute,3:over */
        this.client_sock.state = 0;
    }

    /* 解析请求头 */
    parser_header(data){
        let info = data.shift().split(' ');
        this.header.method  = info[0];
        this.header.path    = info[1];
        this.header.version = info[2];
        this.parser_header_attr(data);
    }
    /* 解析属性 */
    parser_header_attr(data){
        let attr = data.shift().split(':');
        if(!attr || util.Empty(attr[0])) return; //解析结束
        this.header[attr[0]] = attr[1].trim();
        this.parser_header_attr(data);
    }

    /* 设置响应头 */
    set_res_head(key,val){
        this.head_res[key] = val;
    }

    /* 返回响应头属性 */
    write_res_head(){
        //禁止使用 for in
        let attr = Object.keys(this.head_res);
        attr.forEach((key)=>{
            this.client_sock.write(`${key}: ${this.head_res[key]}\r\n`);
        });

    }

    /* 入口 */
    Enter(header_data){
        this.state=1;
        this.parser_header(header_data);
        //设置响应头默认项
        this.set_res_head('Content-type', 'text/html;charset=utf8');
        // this.set_res_head('Content-length', '30');
        // ...
        this.load();
    }

    /* 响应 */
    Emit(body, code='200', msg=''){
        // 返回状态
        this.client_sock.write(`${this.header.version} ${code} ${msg}\r\n`);
        // 响应头属性
        this.write_res_head();
        this.client_sock.write('\r\n');
        //返回正文
        if(body.length){ 
            for(let i=0; i<body.length; i++)
                this.client_sock.write(`${body[i]}\r\n`);
        }
        this.client_sock.state=3;
        //正常结束
        this.client_sock.end();
    }
}

module.exports=Http;